var nickName = '';
var likeNums = 0;
var app = getApp();
// var userInfo;
Page({
    data: {
        currentTabIndex: 0,
        uploadInfo: [],
        studyCard: [],
        loveWall: [],
        lostThing: [],
        focusInput: false,
        height: '',
        isInput: false,
        inputValue: '',
        btnId: '',
        value: '',
        openId: ''
    },
    onLoad() {
        this.getOpenid();
        this.getUserInfo();
        setTimeout(() => {
            // console.log("5s延时");
            this.btngetInfo();
        }, 300);
    },
    onTabsItemTap: function (event) {
        let index = event.currentTarget.dataset.index;
        this.setData({
            currentTabIndex: index
        })
        this.btngetInfo()
    },
    btngetInfo() {

        var db = '';
        switch (this.data.currentTabIndex) {
            case 0:
                db = wx.cloud.database().collection('uploadInfo')
                    .where({
                        _openid: this.data.openId
                    })
                    .orderBy('createTime', 'desc')
                break;
            case 1:
                db = wx.cloud.database().collection('studyCard')
                    .where({
                        _openid: this.data.openId
                    }).orderBy('createTime', 'desc')
                break;
            case 2:
                db = wx.cloud.database().collection('loveWall')
                    .where({
                        _openid: this.data.openId
                    }).orderBy('createTime', 'desc')
                break;
            case 3:
                db = wx.cloud.database().collection('lostThing')
                    .where({
                        _openid: this.data.openId
                    }).orderBy('createTime', 'desc')
                break;
        }
        db.get()
            .then(res => {
                console.log('///请求成功', res);
                switch (this.data.currentTabIndex) {
                    case 0:
                        this.setData({
                            uploadInfo: res.data,
                        })
                        break;
                    case 1:
                        this.setData({
                            studyCard: res.data,
                        })
                        break;
                    case 2:
                        this.setData({
                            loveWall: res.data,
                        })
                        break;
                    case 3:
                        this.setData({
                            lostThing: res.data,
                        })
                        break;
                }
            })
            .catch(res => {
                console.log('请求失败', res);
            })
    },
    previewImg: function (e) {
        let imgData = e.currentTarget.dataset.img;
        // console.log("item2", imgData[0])
        // console.log("item.fileIDs", imgData[1])
        //大图预览
        wx.previewImage({
            //当前显示图片
            current: imgData[0],
            //所有图片
            urls: imgData[1]
        })
    },
    //封装方法获取用户昵称
    getUserInfo() {
        wx.cloud.callFunction({
            name: 'getUserInfo',
            data: {
                openid: 'this.data.openId'
            }
        }).then(res => {
            // console.log("====云函数获取昵称成功", res);
            nickName = res.result.data[0].nickName
            // console.log(nickName);
        }).catch(res => {
            console.log("云函数获取昵称失败", res);
        })

    },
    //封装方法（拿取用户openid）
    getOpenid() {
        wx.cloud.callFunction({
            name: 'getOpenid'
        }).then(res => {
            this.setData({
                openId: res.result.openid
            })
            // console.log("/////调用成功", res);
            // openId = res.result.openid;
            // console.log(openId);
        }).catch(res => {
            console.log("调用失败", res);
        })
    },
    async likeBtn(e) {
        var checkLogin = app.globalData.checkUserInfo
        var db = ''
        const _ = db.command
        var id = e.currentTarget.dataset.id
        var btnlikeIndex = e.currentTarget.dataset.index
        var likelist = [];
        var isHaveLove = false;
        if (checkLogin.nickName == undefined) {
          wx.showToast({
            icon: 'error',
            title: '请先登录',
          })
          return
        }
        wx.vibrateShort({
          type: 'heavy'
        });
        switch (this.data.currentTabIndex) {
          case 0:
            db = wx.cloud.database().collection('uploadInfo')
            break;
          case 1:
            db = wx.cloud.database().collection('studyCard')
            break;
          case 2:
            db = wx.cloud.database().collection('loveWall')
            break;
          case 3:
            db = wx.cloud.database().collection('lostThing')
            break;
        }
    
        let res = await db.doc(id).field({
          likeList: true
        }).get()
        // console.log("==1");
        likelist = res.data.likeList
        // console.log("==2");
        for (var i = 0; i <= likelist.length; i++) {
          if (likelist[i] == checkLogin.nickName) {
            // console.log("==3");
            wx.showToast({
              title: '取消成功',
              icon: 'none',
            })
            likelist.splice(i, 1);
            isHaveLove = true;
            break;
          }
        }
        if (!isHaveLove) {
          // console.log("===3");
          wx.showToast({
            title: '点赞成功',
            icon: 'none',
          })
          likelist.push(checkLogin.nickName)
        }
    
        switch (this.data.currentTabIndex) {
          case 0:
            await wx.cloud.callFunction({
              name: 'smallnoteLike',
              data: {
                id: id,
                likelist: likelist
              }
            })
              .then(res => {
                console.log("点赞成功", res);
              })
              .catch(res => {
                console.log("点赞失败", res);
              })
            // console.log("==4");
            break;
          case 1:
            await wx.cloud.callFunction({
              name: 'studyCardLike',
              data: {
                id: id,
                likelist: likelist
              }
            })
              .then(res => {
                console.log("点赞成功", res);
              })
              .catch(res => {
                console.log("点赞失败", res);
              })
            break;
          case 2:
            await wx.cloud.callFunction({
              name: 'loveWallLike',
              data: {
                id: id,
                likelist: likelist
              }
            })
              .then(res => {
                console.log("点赞成功", res);
              })
              .catch(res => {
                console.log("点赞失败", res);
              })
            break;
          case 3:
            await wx.cloud.callFunction({
              name: 'lostThingLike',
              data: {
                id: id,
                likelist: likelist
              }
            })
              .then(res => {
                console.log("点赞成功", res);
              })
              .catch(res => {
                console.log("点赞失败", res);
              })
            break;
        }
        // console.log("==5");
        this.btngetInfo();
        // console.log("==6");
        wx.hideToast()
    
      },
    inputFocus(e) {
        console.log('键盘弹起', e)
        this.setData({
            height: e.detail.height + 50,
            isInput: true
        })
    },
    inputBlur() {
        console.log('键盘收起')
        this.setData({
            isInput: false
        })
    },

    focusBtn: function (e) {
        console.log(e);
        this.setData({
            btnId: e.currentTarget.dataset.btnid,
            focusInput: true,
            isInput: true
        })
    },

    inputValue(e) {
        console.log(e);
        this.setData({
            inputValue: e.detail.value
        })
    },

    async btnSend() {
        if (this.data.inputValue == '') {
          wx.showToast({
            icon: 'error',
            title: '请输入评论内容',
            duration: 2000
          });
          return
        }else{
          wx.showToast({
            title: '评论成功',
          })
          wx.vibrateShort({
            type: 'heavy'
          });
        }
        var checkLogin = app.globalData.checkUserInfo;
        var commentList = [];
        var db = ''
        this.setData({
          value: ''
        })
        switch (this.data.currentTabIndex) {
          case 0:
            db = wx.cloud.database().collection('uploadInfo')
            break;
          case 1:
            db = wx.cloud.database().collection('studyCard')
            break;
          case 2:
            db = wx.cloud.database().collection('loveWall')
            break;
          case 3:
            db = wx.cloud.database().collection('lostThing')
            break;
        }
        let res = await db.doc(this.data.btnId).field({
          commentList: true
        }).get()
    
        commentList = res.data.commentList
    
        var comment = {
          nickName: checkLogin.nickName,
          value: this.data.inputValue
        }
        commentList.unshift(comment);
        console.log(commentList);
    
        switch (this.data.currentTabIndex) {
          case 0:
            await wx.cloud.callFunction({
              name: 'smallnoteComment',
              data: {
                id: this.data.btnId,
                commentList: commentList
              }
            })
              .then(res => {
                console.log("评论成功", res);
              })
              .catch(res => {
                console.log("评论失败", res);
              })
            break;
          case 1:
            await wx.cloud.callFunction({
              name: 'studyCardComment',
              data: {
                id: this.data.btnId,
                commentList: commentList
              }
            })
              .then(res => {
                console.log("评论成功", res);
              })
              .catch(res => {
                console.log("评论失败", res);
              })
            break;
          case 2:
            await wx.cloud.callFunction({
              name: 'loveWallComment',
              data: {
                id: this.data.btnId,
                commentList: commentList
              }
            })
              .then(res => {
                console.log("评论成功", res);
              })
              .catch(res => {
                console.log("评论失败", res);
              })
            break;
          case 3:
            await wx.cloud.callFunction({
              name: 'lostThingComment',
              data: {
                id: this.data.btnId,
                commentList: commentList
              }
            })
              .then(res => {
                console.log("评论成功", res);
              })
              .catch(res => {
                console.log("评论失败", res);
              })
            break;
        }
    
        this.btngetInfo();
        this.setData({
          inputValue: ''
        })
        wx.hideToast()
      },
    delete(e) {
        var that = this;
        var delId = e.currentTarget.dataset.id;
        var db = '';
        switch (this.data.currentTabIndex) {
            case 0:
                db = wx.cloud.database().collection('uploadInfo')
                break;
            case 1:
                db = wx.cloud.database().collection('studyCard')
                break;
            case 2:
                db = wx.cloud.database().collection('loveWall')
                break;
            case 3:
                db = wx.cloud.database().collection('lostThing')
                break;
        }

        wx.showModal({
            title: '删除',
            content: '你确定删除嘛？',
            success(res) {
                if (res.confirm) {
                    console.log('用户点击确定')
                    db.doc(delId).remove()
                        .then(res => {
                            console.log("删除成功", res);
                        })
                        .catch(res => {
                            console.log("删除失败", res);
                        })
                    setTimeout(() => {
                        that.btngetInfo()
                    }, 300);
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    myPapergetInfo() {

        wx.showToast({
            icon: 'loading',
            title: '加载中...',
        })
        var db = '';
        switch (this.data.currentTabIndex) {
            case 0:
                db = wx.cloud.database().collection('uploadInfo')
                .where({
                    _openid: this.data.openId
                })
                .orderBy('createTime', 'desc').skip(this.data.uploadInfo.length)
                break;
            case 1:
                db = wx.cloud.database().collection('studyCard')
                .where({
                    _openid: this.data.openId
                })
                .orderBy('createTime', 'desc').skip(this.data.studyCard.length)
                break;
            case 2:
                db = wx.cloud.database().collection('loveWall')
                .where({
                    _openid: this.data.openId
                })
                .orderBy('createTime', 'desc').skip(this.data.loveWall.length)
                break;
            case 3:
                db = wx.cloud.database().collection('lostThing')
                .where({
                    _openid: this.data.openId
                })
                .orderBy('createTime', 'desc').skip(this.data.lostThing.length)
                break;
        }
        db.get()
            .then(res => {
                console.log("123",res);
                if (res.data.length == 0) {
                    wx.showToast({
                        icon: 'none',
                        title: '无更多数据',
                        duration: 2000
                    })
                    wx.hideToast();
                    return
                }
                switch (this.data.currentTabIndex) {
                    case 0:
                        this.setData({
                            uploadInfo: this.data.uploadInfo.concat(res.data)
                        })
                        break;
                    case 1:
                        this.setData({
                            studyCard: this.data.studyCard.concat(res.data)
                        })
                        break;
                    case 2:
                        this.setData({
                            loveWall: this.data.loveWall.concat(res.data)
                        })
                        break;
                    case 3:
                        this.setData({
                            lostThing: this.data.lostThing.concat(res.data)
                        })
                        break;
                }
            })
            .catch(res => {
                console.log('请求失败', res);
            })
        wx.hideToast()
    },
    onPullDownRefresh() {
        wx.showNavigationBarLoading()
        setTimeout(() => {
            this.btngetInfo()
            wx.hideNavigationBarLoading()
            wx.stopPullDownRefresh()
        }, 500);
    },
    onReachBottom() {
        console.log("我触底啦");
        wx.showToast({
            icon: 'loading',
            title: '加载中...',
            duration: 1500
        })
        this.myPapergetInfo()
    }
})